<?php

namespace app\admin\controller;

use app\BaseController;
use think\App;
use think\facade\Db;

/**
 * @author xjw
 * @class:TaskProduct 定时任务=>产品操作
 * @method:product 拉取商品  45分钟执行
 * @method:deal_product 处理商品相关
 * @return  
 */


class Webhook extends BaseController
{

    protected $model = null;
    protected $app_key = '';
    protected $app_secret = '';
    protected $code = '';
    protected $access_token = '';
    protected $refresh_token = '';
    
    public function __construct(App $app)
    {
        parent::__construct($app);
    }
    
    /**
    * 方法详情
    * @param array params
    */
    public function index()
    {
        $post['webhook']['address'] = "https://api.fan-zhoubuy.com/admin/Webhook/webhooks";
        // $post['webhook']['topic'] = "orders/edited";
        $post['webhook']['topic'] = "orders/create";
        $post['webhook']['format'] = "json";
        $site = table('site')
            ->where('id', 121)
            ->find();
        $url = $site['site_url'] . "/admin/api/2023-10/webhooks.json";
        $return = $this->posturl($url, $post, $site);
        halt($return);
    }

    /**
    * 方法详情
    * @param array params
    */
    public function webhooks_get()
    {
        $site = table('site')
            ->where('id', 121)
            ->find();
        $url = $site['site_url'] . "/admin/api/2023-10/webhooks.json";
        $return = geturl($url, $site['apikey'], $site['apisecret']);
        halt($return);
    }


    // webhooks回调
    public function webhooks()
    {
        $post = $this->request->post();
        $arr['post'] = json_encode($post,true);
        $arr['type'] = 1;
        table('webhooks')->insert($arr);
        return success('操作成功');
    }
    // https://api.fan-zhoubuy.com/admin/Webhook/webhooks

    function posturl($url, $data = array(), $iscustom = null)
    {
        $data = (is_array($data)) ? json_encode($data, JSON_UNESCAPED_UNICODE) : $data;
        $apikey = $iscustom['apikey'];
        $apisecret = $iscustom['apisecret'];

        $headerArray = array("Content-Type:application/json;", 'Authorization:Basic ' . base64_encode("$apikey:$apisecret"));
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}
